<template>
  <div class="access-record-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">我的出入记录</h1>
      <p class="page-description">查看您和家人的近期出入记录信息</p>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-panel">
      <div class="filter-row">
        <!-- 日期范围选择 -->
        <div class="filter-item">
          <label class="filter-label">日期范围</label>
          <div class="date-range-picker">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              class="date-picker"
            />
          </div>
        </div>

        <!-- 家庭成员筛选 -->
        <div class="filter-item">
          <label class="filter-label">家庭成员</label>
          <el-select v-model="familyMember" placeholder="请选择成员" class="select-control">
            <el-option label="全部成员" value="" />
            <el-option label="业主本人" value="owner" />
            <el-option label="家属" value="family" />
            <el-option label="配偶" value="spouse" />
            <el-option label="父母" value="parent" />
            <el-option label="子女" value="child" />
            <el-option label="其他亲属" value="other_relative" />
            <el-option label="租户" value="tenant" />
            <el-option label="其他" value="other" />
          </el-select>
        </div>
      </div>

      <div class="filter-row">
        <!-- 关键词搜索 -->
        <div class="filter-item search-item">
          <label class="filter-label">关键词</label>
          <el-input
            v-model="keyword"
            placeholder="请输入地点"
            class="search-input"
            suffix-icon="Search"
            @keyup.enter="handleQuery"
          />
        </div>

        <!-- 操作按钮组 -->
        <div class="filter-actions">
          <el-button type="primary" @click="handleQuery" class="query-btn">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset" class="reset-btn"> 重置 </el-button>
        </div>
      </div>
    </div>

    <!-- 数据统计卡片 -->
    <div class="stats-card-container">
      <div class="stat-card">
        <div class="stat-title">本周总记录</div>
        <div class="stat-value">{{ weekTotal }}</div>
        <div class="stat-trend">
          <span class="trend-up" v-if="weekTrend > 0">
            <el-icon><ArrowUp /></el-icon> {{ weekTrend }}%
          </span>
          <span class="trend-down" v-if="weekTrend < 0">
            <el-icon><ArrowDown /></el-icon> {{ Math.abs(weekTrend) }}%
          </span>
          <span class="trend-flat" v-if="weekTrend === 0">
            <el-icon><Minus /></el-icon> 0%
          </span>
          <span class="trend-desc">较上周</span>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-title">本月总记录</div>
        <div class="stat-value">{{ monthTotal }}</div>
        <div class="stat-trend">
          <span class="trend-up" v-if="monthTrend > 0">
            <el-icon><ArrowUp /></el-icon> {{ monthTrend }}%
          </span>
          <span class="trend-down" v-if="monthTrend < 0">
            <el-icon><ArrowDown /></el-icon> {{ Math.abs(monthTrend) }}%
          </span>
          <span class="trend-flat" v-if="monthTrend === 0">
            <el-icon><Minus /></el-icon> 0%
          </span>
          <span class="trend-desc">较上月</span>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-title">异常记录</div>
        <div class="stat-value">{{ abnormalCount }}</div>
        <div class="stat-desc">
          <span v-if="abnormalCount > 0" class="text-warning">
            <el-icon><Warning /></el-icon> 有{{ abnormalCount }}条异常记录
          </span>
          <span v-else>近期无异常记录</span>
        </div>
      </div>
    </div>

    <!-- 数据表格 - 操作类型+操作时间 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        highlight-current-row
        :header-cell-style="headerCellStyle"
        :cell-style="cellStyle"
        class="record-table"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="name" label="成员" min-width="100" />
        <el-table-column prop="relation" label="关系" width="100" align="center">
          <template #default="scope">
            <el-tag type="info">{{ scope.row.relation }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.type === 'person' ? 'primary' : 'success'">
              {{ scope.row.type === 'person' ? '人员' : '车辆' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="出入地点" min-width="140" />
        <!-- 操作类型（进门/出门） -->
        <el-table-column label="操作类型" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.direction === 'in' ? 'success' : 'info'">
              {{ scope.row.direction === 'in' ? '进门' : '出门' }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 操作时间 -->
        <el-table-column prop="time" label="操作时间" min-width="180" />
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click="handleViewDetail(scope.row)"
              class="view-btn"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="记录详情"
      :width="600"
      :before-close="handleCloseDetail"
    >
      <div class="detail-content" v-if="currentRecord">
        <!-- 关键信息行 -->
        <div class="detail-key-row">
          <div class="key-info">
            <span class="key-label">成员：</span>
            <span class="key-value">{{ currentRecord.name }}（{{ currentRecord.relation }}）</span>
          </div>
          <div class="key-info ml-20">
            <span class="key-label">操作类型：</span>
            <span class="key-value">
              <el-tag :type="currentRecord.direction === 'in' ? 'success' : 'info'" size="small">
                {{ currentRecord.direction === 'in' ? '进门' : '出门' }}
              </el-tag>
            </span>
          </div>
        </div>

        <!-- 表格化布局 -->
        <div class="detail-table">
          <div class="detail-row">
            <div class="detail-label">记录类型</div>
            <div class="detail-value">
              {{ currentRecord.type === 'person' ? '人员出入' : '车辆出入' }}
            </div>
            <div class="detail-label">出入地点</div>
            <div class="detail-value">{{ currentRecord.location }}</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">操作时间</div>
            <div class="detail-value">{{ currentRecord.time }}</div>
            <div class="detail-label">验证方式</div>
            <div class="detail-value">{{ currentRecord.verifyMethod }}</div>
          </div>
          <div class="detail-row">
            <div class="detail-label">记录状态</div>
            <div class="detail-value">
              <el-tag :type="currentRecord.status === 'normal' ? 'success' : 'warning'">
                {{ currentRecord.status === 'normal' ? '正常' : '异常' }}
              </el-tag>
            </div>
            <div class="detail-label">记录ID</div>
            <div class="detail-value">{{ currentRecord.id }}</div>
          </div>
          <div v-if="currentRecord.status === 'abnormal'" class="detail-row">
            <div class="detail-label">异常说明</div>
            <div class="detail-value full-width">{{ currentRecord.remark || '无详细说明' }}</div>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false" class="close-btn">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Search, ArrowUp, ArrowDown, Warning, Minus } from '@element-plus/icons-vue'

// 筛选条件
const dateRange = ref<string[]>([])
const familyMember = ref('')
const keyword = ref('')

// 表格数据
const tableData = ref<any[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)

// 统计数据
const weekTotal = ref(32)
const weekTrend = ref(8.5)
const monthTotal = ref(128)
const monthTrend = ref(12.3)
const abnormalCount = ref(1)

// 详情弹窗
const detailVisible = ref(false)
const currentRecord = ref<any>(null)

// 表格样式
const headerCellStyle = computed(() => {
  return {
    'background-color': '#f5f7fa',
    'font-weight': '600',
    'font-size': '14px',
    color: '#1d2129',
  }
})

const cellStyle = computed(() => {
  return {
    'font-size': '13px',
    padding: '12px 0',
  }
})

// 模拟数据
const mockTableData = [
  {
    id: '1001',
    name: '张三',
    relation: '业主本人',
    type: 'person',
    direction: 'in',
    location: '东门入口',
    time: '2023-10-15 08:23:45',
    status: 'normal',
    verifyMethod: '人脸识别',
    remark: '',
  },
  {
    id: '1002',
    name: '李四',
    relation: '配偶',
    type: 'person',
    direction: 'out',
    location: '南门出口',
    time: '2023-10-15 09:12:33',
    status: 'normal',
    verifyMethod: '刷卡',
    remark: '',
  },
  {
    id: '1003',
    name: '张三',
    relation: '业主本人',
    type: 'vehicle',
    direction: 'in',
    location: '北门车辆入口',
    time: '2023-10-15 10:05:18',
    status: 'normal',
    verifyMethod: '车牌识别',
    remark: '',
  },
  {
    id: '1004',
    name: '张小明',
    relation: '子女',
    type: 'person',
    direction: 'out',
    location: '东门出口',
    time: '2023-10-15 11:30:22',
    status: 'abnormal',
    verifyMethod: '刷卡',
    remark: '卡片即将过期，请及时更换',
  },
]

// 页面加载初始化
onMounted(() => {
  fetchAccessRecordList()
  fetchAccessRecordStats()
})

/**
 * 后端接口：获取出入记录列表
 * 作用：根据筛选条件和分页参数，从服务器获取用户及家人的出入记录数据
 * 参数：
 *  - startDate: 开始日期（YYYY-MM-DD，空表示无限制）
 *  - endDate: 结束日期（YYYY-MM-DD，空表示无限制）
 *  - familyMember: 家庭成员筛选值（空表示全部）
 *  - keyword: 地点搜索关键词
 *  - pageNum: 当前页码
 *  - pageSize: 每页条数
 * 返回：
 *  - list: 出入记录数组（含id、name、relation、type等字段）
 *  - total: 总记录数
 */
const fetchAccessRecordList = async () => {
  loading.value = true
  try {
    // 构造请求参数
    const params = {
      startDate: dateRange.value[0] || '',
      endDate: dateRange.value[1] || '',
      familyMember: familyMember.value,
      keyword: keyword.value.trim(),
      pageNum: currentPage.value,
      pageSize: pageSize.value,
    }

    // 实际项目中替换为后端接口请求
    // const response = await axios.get('/api/access/records', { params })
    // const { list, total: totalCount } = response.data

    // 模拟后端返回（实际项目删除此部分）
    let filteredData = [...mockTableData]
    // 家庭成员筛选
    if (familyMember.value) {
      const relationMap: Record<string, string> = {
        owner: '业主本人',
        family: '家属',
        spouse: '配偶',
        parent: '父母',
        child: '子女',
        other_relative: '其他亲属',
        tenant: '租户',
        other: '其他',
      }
      filteredData = filteredData.filter(
        (item) => item.relation === relationMap[familyMember.value],
      )
    }
    // 关键词筛选（地点）
    if (keyword.value) {
      const kw = keyword.value.toLowerCase()
      filteredData = filteredData.filter((item) => item.location.toLowerCase().includes(kw))
    }
    // 日期范围筛选
    if (dateRange.value[0] && dateRange.value[1]) {
      const start = new Date(dateRange.value[0]).getTime()
      const end = new Date(dateRange.value[1]).getTime() + 24 * 60 * 60 * 1000 - 1
      filteredData = filteredData.filter((item) => {
        const recordTime = new Date(item.time).getTime()
        return recordTime >= start && recordTime <= end
      })
    }

    // 赋值数据
    tableData.value = filteredData
    total.value = filteredData.length
  } catch (error) {
    console.error('获取出入记录失败：', error)
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

/**
 * 后端接口：获取出入记录统计数据
 * 作用：从服务器获取本周/本月总记录数、同比趋势及异常记录数
 * 参数：无（基于当前登录用户自动关联数据）
 * 返回：
 *  - weekTotal: 本周总记录数
 *  - weekTrend: 本周较上周变化百分比
 *  - monthTotal: 本月总记录数
 *  - monthTrend: 本月较上月变化百分比
 *  - abnormalCount: 异常记录总数
 */
const fetchAccessRecordStats = async () => {
  try {
    // 实际项目中替换为后端接口请求
    // const response = await axios.get('/api/access/records/stats')
    // const { weekTotal: wt, weekTrend: wtr, monthTotal: mt, monthTrend: mtr, abnormalCount: ac } = response.data

    // 模拟后端返回（实际项目删除此部分）
    weekTotal.value = 32
    weekTrend.value = 8.5
    monthTotal.value = 128
    monthTrend.value = 12.3
    abnormalCount.value = 1
  } catch (error) {
    console.error('获取统计数据失败：', error)
  }
}

/**
 * 后端接口：获取单条记录详情
 * 作用：根据记录ID从服务器获取完整的出入记录详情
 * 参数：
 *  - id: 记录ID
 * 返回：
 *  - 完整的记录对象（包含所有字段）
 */
const fetchRecordDetail = async (id: string) => {
  try {
    // 实际项目中替换为后端接口请求
    // const response = await axios.get(`/api/access/records/${id}`)
    // return response.data

    // 模拟后端返回（实际项目删除此部分）
    return mockTableData.find((item) => item.id === id)
  } catch (error) {
    console.error(`获取记录${id}详情失败：`, error)
    return null
  }
}

// 核心交互方法
const handleQuery = () => {
  currentPage.value = 1
  fetchAccessRecordList()
}

const handleReset = () => {
  dateRange.value = []
  familyMember.value = ''
  keyword.value = ''
  currentPage.value = 1
  pageSize.value = 10
  fetchAccessRecordList()
}

const handleViewDetail = async (row: any) => {
  const detail = await fetchRecordDetail(row.id)
  if (detail) {
    currentRecord.value = detail
    detailVisible.value = true
  }
}

const handleCloseDetail = () => {
  detailVisible.value = false
  currentRecord.value = null
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchAccessRecordList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchAccessRecordList()
}
</script>

<style scoped lang="scss">
.access-record-container {
  padding: 24px;
  background-color: #fafafa;
  min-height: 100vh;
}

// 页面标题
.page-header {
  margin-bottom: 28px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #1d2129;
    margin-bottom: 8px;
  }

  .page-description {
    font-size: 14px;
    color: #86909c;
    margin: 0;
  }
}

// 筛选面板
.filter-panel {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

  .filter-row {
    display: flex;
    align-items: center;
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .filter-item {
    display: flex;
    align-items: center;
    margin-right: 24px;

    &.search-item {
      flex: 1;
      margin-right: 0;
    }

    .filter-label {
      font-size: 14px;
      color: #4e5969;
      margin-right: 12px;
      white-space: nowrap;
      width: 80px;
    }

    .date-picker,
    .select-control,
    .search-input {
      width: 200px;
      height: 36px;
    }

    .search-input {
      width: 100%;
      max-width: 600px;
    }
  }

  .filter-actions {
    margin-left: auto;
    display: flex;
    gap: 12px;

    .query-btn,
    .reset-btn {
      height: 36px;
      padding: 0 16px;
    }
  }
}

// 统计卡片
.stats-card-container {
  display: flex;
  gap: 20px;
  margin-bottom: 24px;

  .stat-card {
    flex: 1;
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition:
      transform 0.3s ease,
      box-shadow 0.3s ease;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    }

    .stat-title {
      font-size: 14px;
      color: #86909c;
      margin-bottom: 12px;
    }

    .stat-value {
      font-size: 28px;
      font-weight: 600;
      color: #1d2129;
      margin-bottom: 8px;
    }

    .stat-trend {
      display: flex;
      align-items: center;

      .trend-up {
        color: #00b42a;
        font-size: 13px;
        margin-right: 8px;
      }

      .trend-down {
        color: #f53f3f;
        font-size: 13px;
        margin-right: 8px;
      }

      .trend-flat {
        color: #86909c;
        font-size: 13px;
        margin-right: 8px;
      }

      .trend-desc {
        font-size: 13px;
        color: #86909c;
      }
    }

    .stat-desc {
      font-size: 13px;
      margin-top: 8px;

      .text-warning {
        color: #faad14;
      }
    }
  }
}

// 表格容器
.table-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 24px;

  .record-table {
    width: 100%;
    border-radius: 8px 8px 0 0;

    ::v-deep .el-table__empty-text {
      padding: 60px 0;
    }

    ::v-deep .el-table__header-wrapper {
      border-bottom: 1px solid #e5e6eb;
    }

    ::v-deep .el-table__body-wrapper {
      &::-webkit-scrollbar {
        width: 6px;
        height: 6px;
      }

      &::-webkit-scrollbar-thumb {
        background-color: rgba(0, 0, 0, 0.1);
        border-radius: 3px;
      }
    }
  }
}

// 分页容器
.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 12px 0;

  ::v-deep .el-pagination {
    .el-pagination__total {
      margin-right: 16px;
      color: #4e5969;
    }

    .el-select .el-input {
      width: 90px;
    }
  }
}

// 按钮样式
::v-deep .el-button {
  border-radius: 4px;
  font-size: 14px;

  &.view-btn {
    color: #1890ff;

    &:hover {
      color: #096dd9;
      background-color: rgba(24, 144, 255, 0.1);
    }
  }
}

// 标签样式
::v-deep .el-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

// 详情弹窗内容样式
.detail-content {
  padding: 8px 0;
}

// 关键信息行
.detail-key-row {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;

  .key-info {
    display: flex;
    align-items: center;

    .key-label {
      font-size: 14px;
      color: #6b7280;
      width: 60px;
    }

    .key-value {
      font-size: 14px;
      color: #1d2129;
      font-weight: 500;
    }
  }

  .ml-20 {
    margin-left: 20px;
  }
}

// 表格化布局
.detail-table {
  width: 100%;

  .detail-row {
    display: flex;
    flex-wrap: nowrap;
    margin-bottom: 14px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .detail-label {
    width: 100px;
    font-size: 14px;
    color: #6b7280;
    text-align: right;
    padding-right: 16px;
    box-sizing: border-box;
  }

  .detail-value {
    flex: 1;
    font-size: 14px;
    color: #1d2129;
    word-break: break-all;
  }

  .full-width {
    flex: 0;
    width: calc(100% - 100px);
  }
}

// 关闭按钮样式
::v-deep .close-btn {
  padding: 0 20px;
}

// 响应式调整
@media (max-width: 1440px) {
  .filter-item {
    margin-right: 16px;

    .filter-label {
      width: 70px;
    }

    .date-picker,
    .select-control {
      width: 160px;
    }
  }
}

@media (max-width: 1200px) {
  .filter-row {
    flex-wrap: wrap;
  }

  .filter-item {
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .stats-card-container {
    flex-wrap: wrap;

    .stat-card {
      flex: 1 1 calc(50% - 10px);

      &:nth-child(3) {
        margin-top: 20px;
      }
    }
  }
}

@media (max-width: 768px) {
  .stats-card-container {
    flex-direction: column;

    .stat-card {
      width: 100%;
      margin-top: 0 !important;
      margin-bottom: 16px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  // 弹窗响应式
  .detail-key-row {
    flex-direction: column;
    align-items: flex-start;

    .ml-20 {
      margin-left: 0;
      margin-top: 8px;
    }
  }

  .detail-table .detail-row {
    flex-direction: column;
  }

  .detail-table .detail-value.full-width {
    width: 100%;
  }
}
</style>
